/**
 * 统一方法
 */
import $ from 'jquery';
import { isEmpty } from 'lodash';
import { HZERO_IMP } from 'utils/config';
import intl from 'utils/intl';
import notification from 'utils/notification';

/**
 * 关闭浏览器当前窗口（非门户tab窗口）
 */
export function closeWindows() {
  window.opener = null;
  window.open('about:blank', '_self');
  window.close();
}

/**
 * 根据身份证获取生日（YYYY-MM-DD）、年龄和性别
 * @param IDCard 18位身份证号码
 * @return {result} 包含生日、年龄、性别
 */
export function analyzeIDard(IDCard) {
  const result = {};
  if (!IDCard) {
    return result;
  }
  // 获取性别
  if (parseInt(IDCard.substr(16, 1), 10) % 2 === 1) {
    result.sex = '1';
  } else {
    result.sex = '2';
  }
  // 获取出生年月日
  const birthYear = IDCard.substr(6, 4);
  const birthMonth = IDCard.substr(10, 2);
  const birthDay = IDCard.substr(12, 2);
  result.birthDay = `${birthYear}-${birthMonth}-${birthDay}`;

  const nowDate = new Date();
  const nowYear = nowDate.getFullYear();
  const nowMonth = nowDate.getMonth() + 1;
  const nowDay = nowDate.getDate();

  // 计算年龄
  let age = nowYear - birthYear;
  if (nowMonth < birthMonth || (nowMonth === birthMonth && nowDay < birthDay)) {
    age--;
  }
  result.age = age;

  return result;
}

export function getCodeMeaning(value, code = []) {
  let result;
  if (value && !isEmpty(code)) {
    const codeList = code.filter(n => n.value === value);
    if (!isEmpty(codeList)) {
      result = codeList[0].meaning;
    }
  }
  return result;
}

/**
 * openwindow - 打开新窗口预览文件
 * @param {string} url - 文件服务地址
 */
export function openwindow(url) {
  return window.open(
    url,
    '',
    'height=600,width=900,top=50,left=50,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=no'
  );
}

/**
 * viewPDF - 将其他文件转化为PDF格式预览
 * @param {string} url - 文件url
 * @param {boolean} wm - 是否显示水印
 * @param {number} convertType - 文件转化类型  1: 文档格式 -> html，14: pdf -> html
 * 3:文档格式 -> pdf，34:pdf -> pdf
 */
export function viewPDF(url = null, wm = false, convertType = 34) {
  $.ajax({
    url: OA_PREVIEW,
    data: {
      downloadUrl: url,
      convertType,
      isDownload: 1,
      wmContent: wm ? loginName : null,
      antiDownload: 1,
      isCopy: 1,
      htmlTitle: '预览',
      wmSize: 20,
      showFooter: 0,
    },
    dataType: 'json',
    type: 'POST',
    success(res) {
      if (res.data) {
        openwindow(res.data[0]);
      } else {
        notification.error({
          message: '出错了！',
          description: res.message,
        });
      }
    },
    error() {
      notification.error({ message: '出错了！', description: '预览服务错误！' });
    },
  });
}

/*
 * 附件信息下载成word格式/Excel格式
 * @param { string } rootId -- 节点id
 * @param { string } type -- 下载的文件类型
 */
export function htmlExport(rootId, type) {
  let doc = '';
  doc += '<div>';
  const html = document.getElementById(rootId).innerHTML;
  doc += html;
  doc += '</div>';
  const a = document.body.innerHTML;
  let docFile = `<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:${a}' xmlns='http://www.w3.org/TR/REC-html40'>`;
  docFile = `${docFile}
      <head><!--[if gte mso 9]><xml><x:ExcelWorkbook>
      <x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name>
      <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions>
      </x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml>
      <![endif]--></head>${doc}</body></html>
    `;
  const base64data = `base64,${window.btoa(unescape(encodeURIComponent(docFile)))}`;
  const blob = dataURLtoBlob(`base64,${window.btoa(unescape(encodeURIComponent(docFile)))}`);
  if ('msSaveOrOpenBlob' in navigator) {
    // ie使用的下载方式
    window.navigator.msSaveOrOpenBlob(blob, `下载.${type}`);
  } else if (type === 'doc') {
    window.location.href = `data:application/msword;${base64data}`;
  } else if (type === 'excel') {
    window.location.href = `data:application/vnd.ms-excel;${base64data}`;
  }
}

// todo 调整消息返回 -- 重写
export function getResponse(response, errorCallback) {
  if (response && response.failed === true) {
    if (errorCallback) {
      errorCallback(response);
    } else {
      const msg = {
        message: intl.get('hzero.common.notification.error').d('操作失败'),
        description: response.message,
      };
      switch (response.type) {
        case 'info':
          notification.info(msg);
          break;
        case 'warn':
          if (response.code === 'error.optimistic_lock') {
            msg.description = `${msg.description}，请刷新页面重新尝试`;
            notification.warning(msg);
            break;
          }
          notification.warning(msg);
          break;
        case 'error':
        default:
          notification.error(msg);
          break;
      }
    }
  } else {
    return response;
  }
}


